import { NextResponse } from 'next/server';
import { cookies } from 'next/headers';
import prisma from '@/app/lib/prisma';
import { verifyToken } from '@/app/lib/auth';

export async function GET() {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const profile = await prisma.user.findUnique({
      where: { id: payload.userId },
      select: {
        email: true,
        name: true,
        gender: true,
        age: true,
        height: true,
        weight: true,
        healthGoal: true,
      },
    });

    return NextResponse.json({ profile });
  } catch (error) {
    console.error('获取用户资料错误:', error);
    return NextResponse.json(
      { message: '获取用户资料失败' },
      { status: 500 }
    );
  }
}

export async function PUT(request: Request) {
  try {
    const cookieStore = await cookies();
    const token = cookieStore.get('auth-token')?.value;

    if (!token) {
      return NextResponse.json(
        { message: '请先登录后再使用此功能' },
        { status: 401 }
      );
    }

    const payload = verifyToken(token);
    if (!payload) {
      return NextResponse.json(
        { message: '登录已过期，请重新登录' },
        { status: 401 }
      );
    }

    const data = await request.json();

    const updatedProfile = await prisma.user.update({
      where: { id: payload.userId },
      data: {
        name: data.name,
        gender: data.gender,
        age: data.age,
        height: data.height,
        weight: data.weight,
        healthGoal: data.healthGoal,
      },
    });

    return NextResponse.json({ 
      message: '更新成功',
      profile: updatedProfile 
    });
  } catch (error) {
    console.error('更新用户资料错误:', error);
    return NextResponse.json(
      { message: '更新用户资料失败' },
      { status: 500 }
    );
  }
} 